package cm.cool.web.service.news;

import java.io.File;
import java.io.FileOutputStream;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;

import cm.cool.system.qiniu.QiniuUpload;
import cm.cool.web.bean.News;
import cm.cool.web.data.NewsMapper;
import cm.cool.web.util.cookie.CookieOp;
import cm.cool.web.util.respon.PaginationDto;
import cm.cool.web.util.respon.R;
import cm.cool.web.util.respon.ResultEncoding;
import cm.cool.web.util.tokencache.TokenUtil;

/**
 * 咨讯的增删改成
 * @author fangzhenxing
 * time：2017年10月18日14:17:27
 */
@Service
public class NewsService {
		
	@Autowired
	NewsMapper newsMapper;
	
	//cookie名称
	@Value("${cookie.name}")
	private String cookieName;
		
	/**
	 * 查找所有
	 * @param news
	 * @param paginationDto
	 * @return
	 */
	public R selectByAll(News news,PaginationDto paginationDto){
		R r=new R();
		
		try {
			PageHelper.startPage(paginationDto.getCurrentPageNum(), paginationDto.getPerPageSize());
			paginationDto.setEntitys(newsMapper.selectByAll(news));
			int count = newsMapper.selectByAllCount(news);
			paginationDto.setTotalCount(count);
			paginationDto.setTotalPageNum((int)Math.ceil((count*1.0) / paginationDto.getPerPageSize()));
			r.setData(paginationDto);
		} catch (Exception e) {
			e.printStackTrace();
			r.setCode(ResultEncoding.R_ERR);
			r.setMsg("查询异常");
			return r;
		}
		return r;
	}
	
	
	/**
	 * 添加一个咨讯
	 * @param record
	 * @return
	 */
	public R insertSelective(News record,HttpServletRequest httpServletRequest){
		
		R r=new R();
		
		try {
			
			//数据校验
			if( R.isNull(record.getNewsTitle()) || R.isNull(record.getNewsText())){
				  r.setCode(ResultEncoding.R_PARAMETER);
				  r.setMsg("添加参数不能为空");
				  return r;
			}
				
			
			//拿到token的值
	        String tokenValue=CookieOp.getCookie(httpServletRequest, cookieName);
		    record.setAdminId(TokenUtil.getAdminId(tokenValue));
			record.setId(UUID.randomUUID().toString());
			newsMapper.insertSelective(record);
			r.setMsg("添加成功");
		} catch (Exception e) {
			e.printStackTrace();
			r.setCode(ResultEncoding.R_ERR);
			r.setMsg("系统错误");
			return r;
		}
		
		return r;
	}
	
	
	/***
	 * 修改一个咨讯
	 * @return
	 */
	public R updateByPrimaryKeySelective(News record){
		
		R r=new R();
		try {
			//数据校验
			if(R.isNull(record.getId()) || R.isNull(record.getAdminId()) || R.isNull(record.getNewsText()) || R.isNull(record.getNewsTitle())){
				 r.setCode(ResultEncoding.R_PARAMETER);
				 r.setMsg("修改参数不能为空");
				 return r;
			}
			newsMapper.updateByPrimaryKeySelective(record);
			r.setMsg("修改成功");
		} catch (Exception e) {
			e.printStackTrace();
			r.setCode(ResultEncoding.R_ERR);
			r.setMsg("系统错误");
			return r;
		}
		
		return r;
		
	}
	
	/**
	 * 删除一个咨讯
	 * @return
	 */
	public R deleteByPrimaryKey(News record){
		R r=new R();
		try {
			if(R.isNull(record.getId())){
				r.setCode(ResultEncoding.R_PARAMETER);
				r.setMsg("修改参数不能为空");
			    return r;
			}
			
			newsMapper.deleteByPrimaryKey(record.getId());
			r.setMsg("删除成功");
		} catch (Exception e) {
			e.printStackTrace();
			r.setCode(ResultEncoding.R_ERR);
			r.setMsg("系统错误");
			return r;
		}
		
		return r;
	}
	
	/**
	 * 拿到妻孥的token
	 * @return
	 */
	public String createToken(){
		return QiniuUpload.auth.uploadToken(QiniuUpload.BUCKET);
	}
	
	/**
	 * 往七牛添加一个图片
	 * @return
	 */
	public String  uploadImg(MultipartFile file,HttpServletRequest request){
		
        String fileName = file.getOriginalFilename();
        String filePath = request.getSession().getServletContext().getRealPath("imgupload/");
        System.out.println("+===========================拿到的路径是："+filePath);
        try {
            uploadFile(file.getBytes(), filePath, fileName);
        } catch (Exception e) {
        	e.printStackTrace();
        }
        return filePath;
	}
	
	
	/**
	 * 上传工具方法
	 * @param file
	 * @param filePath
	 * @param fileName
	 * @throws Exception
	 */
	public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception { 
        File targetFile = new File(filePath);  
        if(!targetFile.exists()){    
            targetFile.mkdirs();    
        }       
        FileOutputStream out = new FileOutputStream(filePath+fileName);
        out.write(file);
        out.flush();
        out.close();
    }
}
